package router

import (
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"good.house/config"
	_ "good.house/docs" // docs 是 swag init 生成的
	"good.house/internal/controller"
	"good.house/internal/middleware"
	"good.house/internal/repository"
	"good.house/internal/service"
	"gorm.io/gorm"
)

func getUserCtl(db *gorm.DB, rdb *redis.Client) (*controller.UserController, *repository.UserRepository) {
	repository := repository.NewUserRepository(db, rdb)
	service := service.NewUserService(repository)
	ctl := controller.NewUserController(service)
	return ctl, repository
}

func getPublishCtl(db *gorm.DB, rdb *redis.Client) *controller.PublishController {
	repository := repository.NewPublishRepository(db, rdb)
	service := service.NewPublishService(repository)
	ctl := controller.NewPublishController(service)
	return ctl
}

// func getGinLogOut(cfg *config.Config) io.Writer {
// 	if cfg.Env == config.EnvDevelopment {
// 		return nil
// 	} else if cfg.Env == config.EnvTest || cfg.Env == config.EnvProduction {
// 	}
// }

func getListCtl(db *gorm.DB, rdb *redis.Client) *controller.ListController {
	repository := repository.NewListRepository(db)
	service := service.NewListService(repository)
	ctl := controller.NewListController(service)

	return ctl
}

func SetupRouter(db *gorm.DB, rdb *redis.Client, cfg *config.Config) *gin.Engine {
	// 用户相关
	userCtl, repository := getUserCtl(db, rdb)

	// 发布相关
	publishCtl := getPublishCtl(db, rdb)

	// 获取列表相关
	listCtl := getListCtl(db, rdb)

	r := gin.New() // 不使用默认中间件

	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	r.Use(middleware.GinLogMiddleWare())

	r.Use(gin.Recovery()) // 添加 Recovery 中间件

	// 配置文件中间件
	r.Use(middleware.ConfigMiddleware(cfg))

	public := r.Group("/api")
	{
		public.POST("/reqister", userCtl.Register)
		public.POST("/login", userCtl.Login)
	}

	// 需要认证的路由
	authorized := r.Group("/api")
	authorized.Use(middleware.AuthMiddleware(repository))

	{
		authorized.POST("/publish", publishCtl.Publish)
	}

	{
		authorized.POST("/getRentList", listCtl.GetRentList)
	}

	return r
}
